package com.tp.server;

import java.io.IOException;
import java.util.Scanner;

/**
 * Server Manager: controla al servidor con los comandos:
 * - start: inicia servidor DNS
 * - stop: detiene servidor DNS
 * - close: cierra Server Manager
 * @author Franke Oviedo Triay
 * 
 *
 */
public class ServerManager {

	private static final String START = "start";
	private static final String STOP = "stop";
	private static final String CLOSE = "close";

	public static void main(String[] args) throws IOException, InterruptedException {
		
		boolean runServer = true;
		Scanner in = new Scanner(System.in);
		String serverCommand;
		DnsResolver dnsResolver = null;
		welcomeScreen();
		while (runServer) {
			//Toma comando del input
			serverCommand = in.nextLine();
			
			if (START.equalsIgnoreCase(serverCommand)) {	
				
				if(dnsResolver == null){
					
					//Instancia el servidor
					dnsResolver = new DnsResolver();
					dnsResolver.start();
					System.out.println("Servidor iniciado");
					
				}else{
					
					System.out.println(":: el Servidor ya fue iniciado! ::");
					
				}
				
			} else if (STOP.equalsIgnoreCase(serverCommand)) {
				
				
				desconectarServidorDns(dnsResolver);
				dnsResolver= null;
				
			} else if (CLOSE.equalsIgnoreCase(serverCommand)) {
				
				
				desconectarServidorDns(dnsResolver);
				runServer = false;
				System.out.println(":: Cerrando Server Manager ::");
				
			}
			serverCommand = "";
			
		}
	}
	
	/**
	 * Desconecta el servidor en caso de parar el servidor DNS o cerrar el manager del servidor.
	 * @param dnsResolver
	 */
	public static void desconectarServidorDns(DnsResolver dnsResolver){
		if (dnsResolver != null && dnsResolver.isAlive()) {
			//Detiene servidor
			System.out.println(":: Desconectando servidor ::");
			dnsResolver.desconectar();
			dnsResolver = null;
		} else {
			
			System.out.println(":: Servidor no iniciado! ::");
			
		}
	}
	
	/**
	 * Muestra mensaje inicial con comandos.
	 */
	public static void welcomeScreen() {
		System.out
				.println("------------------------------------------------------");
		System.out
				.println("|                   DNS SERVER                        |");
		System.out
				.println("| Comandos:                                           |");
		System.out
				.println("| -start: Inicia el servidor                          |");
		System.out
				.println("| -stop: Detiene el servidor                          |");
		System.out
				.println("| -close: Cierra la aplicacion                        |");
		System.out
				.println("------------------------------------------------------");
	}

}
